package cn.edu.scau.cmi.wangmaoren.comprehension.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.scau.cmi.wangmaoren.comprehension.domain.Teacher;
import cn.edu.scau.cmi.wangmaoren.comprehension.util.HibernateFactory;

public class TeacherDAO {
	private static final Logger log = LoggerFactory.getLogger(TeacherDAO.class);
	// property constants
	public static final String NAME = "name";
	private Session session;

	private Session getSession() {
		session=HibernateFactory.getSession();
		return session;
	}
	public void save(Teacher transientInstance) {
		log.debug("saving Teacher instance");
		try {
			getSession();
			Transaction transaction = session.beginTransaction();
			session.save(transientInstance);
			transaction.commit();
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}
	public void update (Teacher transientInstance) {
		log.debug("updating Teacher instance");
		try {
			getSession();
			Transaction transaction = session.beginTransaction();
			session.update(transientInstance);
			log.debug("update successful");
			transaction.commit();
		}catch(Exception e) {
			log.error("update failed", e);
			throw e;
		}
	}
	public void delete(Teacher persistentInstance) {
		log.debug("deleting Teacher instance");
		try {
			getSession();
			Transaction transaction = session.beginTransaction();
			session.delete(persistentInstance);
			log.debug("delete successful");
			transaction.commit();
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}
	public Teacher findById(Long id) {
		log.debug("getting Teacher instance with id: " + id);
		try {
			Teacher instance = (Teacher) getSession().get(Teacher.class, id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	public List<Teacher> findAll() {
		try {
			String queryString = "from Teacher";
			getSession();
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}
	public void attachDirty(Teacher instance) {
		log.debug("attaching dirty Teacher instance");
		try {
			getSession();
			Transaction transaction = session.beginTransaction();
			session.saveOrUpdate(instance);
			log.debug("attach successful");
			transaction.commit();
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
}
